package org.example.domain.strategy.service.rule.tree.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 奖品次数锁节点
 */
@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {


    @Resource
    private IStrategyRepository repository;

    //用户抽奖次数，后续从数据库/redis读取
    private Long userRaffleCount=10L;
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{}",userId,strategyId,awardId);

        long raffleCount=0L;
        try {
            raffleCount=Long.parseLong(ruleValue);

        }catch (Exception e){
            throw new RuntimeException("规则过滤-次数锁异常 ruleValue: "+ruleValue+"配置不正确");
        }

        //查询用户抽奖次数
        Integer userRaffleCount=repository.queryTodayUserRaffleCount(userId,strategyId);

        //用户抽奖次数大于规定限定值放行
        if(userRaffleCount>=raffleCount){
            log.info("规则锁放行");
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .build();
        }

        //小于则拦截
        log.info("规则锁拦截");
        return  DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();
    }
}
